<?php

namespace App\Jobs;

use App\Models\system\NewsMiddleModel;
use App\Models\system\NewsModel;
use App\Models\users\UsersModel;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class NewsExample implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     */
    private $uid;
    public function __construct($uid)
    {
        $this->uid = $uid;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        try {
            $lists = NewsModel::get()->toArray();
            if ($this->uid) {
                foreach ($lists as $value) {
                    $middle = NewsMiddleModel::where('uid', $this->uid)->where('news_id', $value['id'])->first();
                    if (!$middle) {
                        NewsMiddleModel::create([
                            'uid' => $this->uid,
                            'news_id' => $value['id'],
                            'is_browse' => 0,
                            'is_delete' => 0,
                        ]);
                    }
                }
            } else {
                $user = UsersModel::get()->toArray();
                foreach ($user as $value) {
                    foreach ($lists as $vv) {
                        $middle = NewsMiddleModel::where('uid', $value['id'])->where('news_id', $vv['id'])->first();
                        if (!$middle) {
                            NewsMiddleModel::create([
                                'uid' => $value['id'],
                                'news_id' => $vv['id'],
                                'is_browse' => 0,
                                'is_delete' => 0,
                            ]);
                        }
                    }
                }
            }
        } catch (\Exception $e) {
            log::error(date('Y-m-d h:i:s',time()).' 平台消息推送失败:'.$e->getMessage());
        }
    }
}
